<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form class="search-form" action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow=false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result 
    v-if="isResultShow"
    :searchText="searchText"
    />

    <!-- 联想建议 -->
    <search-suggestion 
    v-else-if="searchText"
    :searchText="searchText"
    @search="onSearch"
    />

    <!--  搜索历史记录-->
    <search-history 
    @search="onSearch" 
    @deleteAllHistory="searchHistories=[]" 
    :searchHistories="searchHistories" 
    v-else
    />

  </div>
</template>

<script>
  import SearchHistory from './component/search-history'
  import SearchSuggestion from './component/search-suggestion'
  import SearchResult from './component/search-result'
  import {getItem,setItem} from '@/utils/storage';

  export default {
    name:"SearchPage",
    data(){
      return {
        searchText:'', //搜索内容
        isResultShow:false,  //控制搜索结果是否显示
        searchHistories:getItem('TOUTIAO_SEARCH_HISTORY')||[],  //搜索的历史记录
      }
    },
    components:{
      SearchHistory,
      SearchSuggestion,
      SearchResult
    },
    methods: {
      onSearch(val) {
        //更新文本框内容
        this.searchText=val
        //存储搜索历史记录
        //不要有重复历史记录,最新的排在最前
        const index=this.searchHistories.indexOf(val)
        if(index!==-1){
          this.searchHistories.splice(index,1)
        }
        this.searchHistories.unshift(val)
        // 渲染搜索结果
        this.isResultShow=true
      },
      onCancel() {
        // 点击取消,则返回前一页
        this.$router.back()
      },
      
    },
    watch:{
      searchHistories(val){
        
        setItem('TOUTIAO_SEARCH_HISTORY',val)
      }
    }


  }
</script>

<style lang='less' scoped>
.search-container{
  padding-top: 108px;
  .search-form{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}

</style>